package fm.dongman.modellib.source

import fm.dongman.animefm.contractlib.BaseDataSource
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.SheetCreateContract
import fm.dongman.modellib.RemoteHelper
import fm.dongman.modellib.StaticArea.StaticUrl
import fm.dongman.modellib.model.SheetModel
import org.json.JSONObject

/**
 * 漫单创建
 * Created by shize on 2017/12/2.
 */
class SheetCreateRepository private constructor(): SheetCreateContract.ISheetCreateDataSource {
    private var mSheetId: String? = null

    override fun setEditSheetId(sheetId: String) {
        mSheetId = sheetId
    }

    override fun getData(callback: BaseDataSource.LoadSourceCallback<IModel.ISheetModel>) {
        if (mSheetId == null) {
            callback.onDataLoadFiled()
            return
        }
        SheetInfoRepository.getInstance().getData(callback)
    }

    override fun editSheet(sheet: IModel.ISheetModel, callback: BaseDataSource.LoadSourceCallback<String?>) {
        val json = getSheetJson(sheet, TYPE_EDIT)
        if (json == null) {
            callback.onDataLoadFiled()
            return
        }
        callback.onDataLoaded(null)
    }

    override fun createSheet(userId: String, sheet: IModel.ISheetModel, callback: BaseDataSource.LoadSourceCallback<String?>) {
        val json = getSheetJson(sheet, TYPE_CREATE)
        if (json == null) {
            callback.onDataLoadFiled()
            return
        }
        callback.onDataLoaded(null)
    }

    /**
     * 获取漫单提交结果
     * @param sheet 漫单信息
     * @param type 操作类型
     */
    private fun getSheetJson(sheet: IModel.ISheetModel, type: String): JSONObject? {
        val sheetInfo = sheet as SheetModel
        return RemoteHelper.instance.parsePostUrl(StaticUrl.EDIT_SHEET_INFO, mapOf(
                Pair("session_key", StaticUrl.TOKEN_KEY), Pair("name", sheetInfo.mandanTitle),
                Pair("summary", sheetInfo.summary), Pair("type", type),
                Pair("mandan_id", sheetInfo.mandanId)))
    }

    override fun refreshData() {
    }

    override fun saveData(dataModel: IModel.ISheetModel) {
    }

    override fun offLine() {
    }

    companion object {
        val TYPE_CREATE = "create"
        val TYPE_EDIT = "edit"
        val TYPE_DELETE = "delete"
        var INSTANCE:SheetCreateRepository? = null

        fun getInstance():SheetCreateRepository{
            if (INSTANCE == null){
                INSTANCE = SheetCreateRepository()
            }
            return INSTANCE!!
        }
    }
}